// Tooltips
function nocounts() {
	$('.no-count').tooltip({
		showURL: false,
		track: true,
		fade: 150,
		top: -40,
		left: -100
	}).css('cursor', 'pointer');
	$('#tooltip').addClass('bold');
}
function hascounts() {
	$('.count-tooltip').tooltip({
		showURL: false,
		track: true,
		fade: 150,
		top: -100,
		left: -380,
		//extraClass: "count-tooltip-wrapperr",
		bodyHandler: function () {
			$('#tooltip').addClass('count-tooltip-wrapper');
			return $(this).find('.tooltip-simpletable').clone();
		}
	}).css('cursor', 'pointer');
}

// onMouseOver/ onMouseOut
$(function () {
	$("#startDate").datepicker();
	$("#endDate").datepicker();
});

function reasignOpen(leadId, userId) {
	$('#viewleadId').val(leadId);
	$('#username').text($('#user-lead' + leadId).attr("title"));

	// Reset combobox state
	var el = $("#popup #userOptionSelect");
	if (el.length && el.editableSelect("select").length) {
		//el.editableSelect("select").get(0).selectedIndex = 0;
		$(el.editableSelect("select").get(0)).val(userId);
		el.editableSelect("refreshState");
	}

	// Show popup
	$('#popup').showPopup({
		width: 520
	});
	$('#fancybox-overlay').show();
}
function confirmPopup(leadId) {
	$('#leadId').val(leadId);
	$('#leadName').text($('#lead' + leadId).attr("rel"));

	// Show popup
	$('#confirmDelete').showPopup({
		width: 400
	});
	$('#fancybox-overlay').show();
}

function closePopup() {
	$('#popup').hide();
	$('#confirmDelete').hide();
	$('#fancybox-overlay').hide();
	$(".fancybox-wrap").hide();
}

function dialIDCallPhone(leadId) {
	var phone = $('#callphone_' + leadId).attr("rel");
	var dataPost = { "leadId": leadId, "leadPhone": phone };

	// Ajax call function
	// Handle reponse
	$.ajax({
	    type: "POST",
	    url: "/Lead/PlaceACall",
	    data: dataPost,
	    dataType: "json",
	    success: function (data, textStatus, jqXHR) {
	        // Stop progress bar
	        hideProcess();
	        console.log("success");
	        if (data.Error == undefined || data.Error == null) {

	        }
	        else {
	            showDialError();
	        }
	    },
	    error: function (xhr, status, error) {
	        // Stop progress bar
	        console.log("error");
	        hideProcess();
	        showPopupError();
	    }
	});
}


function openLead(leadId) {
	$('#viewleadId').val(leadId);
	$('#username').text($('#user-lead' + leadId).attr("rel"));
}

function openDelLead(leadId) {
	$('#leadId').val(leadId);
	$('#leadName').text($('#lead' + leadId).attr("rel"));
}


var prioritizedView = false;

var viewModel = new function () {
	// Check view is Prioritized
	var isPrioritized = $('#PrioritizedForm').val();
	if (isPrioritized != undefined && isPrioritized != null && isPrioritized == 'true') {
		prioritizedView = true;
	}

	this.LastUpdate = ko.observable(data.LastUpdateTime);

	// Configs
	this.Leads = ko.observableArray([]);
	if (data.LeadsourceList != null) {
		this.Leads = ko.observableArray(data.LeadsourceList);
	}
	this.PageSize = ko.observable(data.PageSize);
	this.CurrentPageIndex = ko.observable(data.TotalPages == null || data.TotalPages == 0 ? 0 : 1);
	this.MaxPageIndex = ko.observable(data.TotalPages);
	this.ColName = ko.observable("DateAdded");
	this.SortOrder = ko.observable("desc");
	this.VisibleUserColumn = ko.observable(data.VisibleUserColumn);

	this.FieldName1 = ko.observable(data.FieldName1);
	this.FieldName2 = ko.observable(data.FieldName2);

	// Calculate condition to add class
	// Fix issue in chrome
	this.LineClass = function (index, length, status) {
		if (status != "") {
			if (index == length)
				return "line new last";
			else
				return "line new";
		}
		else {
			if (index == length)
				return "line last";
			else
				return "line";
		}
	}

	// Total Records
	this.TotalLead = ko.observable(data.TotalLead);
	this.PageText = ko.computed(function () {
		var total = this.TotalLead();
		if (total == 1)
			return total + " lead found";
		else
			return total + " leads found";

	}, this);

	/*this.PageSizeText = ko.observable("");
	this.PageCurrentText = ko.observable("");

	*/
	this.PageSizeText = ko.computed(function () {
		var pagevalue = this.PageSize().toString().replace(/\s/g, '');
		var pagesize = parseInt(pagevalue, 10);
		if (!IsNumeric(pagevalue))
			return "* Please enter a number between 1 - 100";
		else if (pagesize.toString() == 'NaN' || pagesize < 1 || pagesize > 100) {
			return "* Please enter a number between 1 - 100";
		}
		else {
			return "";
		}
	}, this);
	this.PageCurrentText = ko.computed(function () {
		var pagevalue = this.CurrentPageIndex().toString().replace(/\s/g, '');
		var pageindex = parseInt(pagevalue, 10);

		if (this.TotalLead().length != 0) {
			if (!IsNumeric(pagevalue) || pagevalue == "" || pagevalue.toString() == 'NaN' || !IsNumeric(pagevalue) || pageindex < 1 || pageindex > this.MaxPageIndex()) {
				return "* Please enter a number between 1 - " + this.MaxPageIndex() + " ";
			}
			else {
				return "";
			}
		}
		return "";

	}, this);


	// Paginate
	this.PrevPage = function () {
		var page = parseInt(this.CurrentPageIndex());
		if (page > 1) {
			this.CurrentPageIndex(page - 1);
			LoadDataFromServer(0);
		}
	}
	this.PrevButtonClass = ko.computed(function () {
		var page = parseInt(this.CurrentPageIndex());
		if (page > 1) {
			return "btn btn-prev-arrow prev-active";
		}
		else {
			return "btn btn-prev-arrow";
		}
	}, this);

	this.NextPage = function () {
		var page = parseInt(this.CurrentPageIndex());
		if (page < this.MaxPageIndex()) {
			this.CurrentPageIndex(page + 1);
			LoadDataFromServer(0);
		}
	}
	this.NextButtonClass = ko.computed(function () {
		if (this.CurrentPageIndex() >= this.MaxPageIndex() || this.MaxPageIndex() == 1) {
			return "btn btn-next-arrow next-disabled";
		}
		else {
			return "btn btn-next-arrow";
		}
	}, this);

	this.DisableNextButton = ko.computed(function () {
		if (IsNumeric(this.CurrentPageIndex())) {
			var pageIndex = parseInt(this.CurrentPageIndex(), 10);
			var maxPage = parseInt(this.MaxPageIndex());

			if (pageIndex >= maxPage)
				return 1;
			else
				return 0;
		}
		return 0;
	}, this);

	// Sort by Colum/Order
	function SetOrder(event, ColName) {
		if (this.ColName() === ColName) {
			this.SwitchSortOrder();
		} else {
			this.ColName(ColName);
			this.SortOrder("asc");
		}
		SetTHClass(ColName, event);
		LoadDataFromServer(0);
	}
	this.SetOrder = SetOrder; // Set to an knockout object
	function SwitchSortOrder() {
		if (this.SortOrder() === "asc") {
			this.SortOrder("desc");
		} else {
			this.SortOrder("asc");
		}
	}
	this.SwitchSortOrder = SwitchSortOrder;

	function SetTHClass(colName, event) {
		$("div.title").parent().find(".sort_wrapper").children("span").removeClass("asc");
		$("div.title").parent().find(".sort_wrapper").children("span").removeClass("desc");

		if (viewModel.SortOrder() === "asc") {
			$("#" + colName).children("span").addClass("asc");
		} else {
			$("#" + colName).children("span").addClass("desc");
		}
	}

	this.UserOption = ko.observable();
	this.UserOptions = ko.observableArray(data.UserAssignFilter == null ? [] : data.UserAssignFilter);

	// Assign view lead items to user
	this.AssignToUser = function () {
		var userId = $("#userOptionSelect").editableSelect('value');
		var leadId = $('#viewleadId').val();
		if (parseInt(userId) > 0)
			LoadDataFromServer(userId, leadId);
	};

	// Delete view lead items
	this.DeleteLead = function () {
		var leadId = $('#leadId').val();
		LoadDataFromServer(0, leadId);
	};

	this.RunSomething = function (viewModel, event) {
		LoadDataFromServer(0, 0);
	}

	this.UserList = ko.observableArray(data.UserFilter);
	this.LeadSourceList = ko.observableArray(data.CampaignFilter);
	this.StatusList = ko.observableArray(data.StatusFilter);
	this.RangeList = ko.observableArray(data.RangeFilter);
	this.GoButton = ko.observable(false);

	this.GoFilter = function () {
		FirstFilterGo = true;
		this.GoButton(true);

		LoadDataFromServer(0, 0);
	}

	this.ButtonQickAction = function (lead) {
		var dataPost = { "id": lead.Leadid };

		// Progress
		openProcess();

		// Ajax call function
		// Handle reponse
		$.ajax({
			type: "POST",
			url: "/Lead/QuickAction",
			data: dataPost,
			dataType: "json",
			success: function (data, textStatus, jqXHR) {
				// Stop progress bar
				hideProcess();

				if (data.Error == undefined || data.Error == null) {
					if (!prioritizedView)
						window.location.href = "/Lead";
					else
						window.location.href = "/Lead/Priority";
				}
				else {
					showPopupError();
				}
			},
			error: function (xhr, status, error) {
				// Stop progress bar
				hideProcess();
				showPopupError();
			}
		});
	}


	// Load data
	function LoadDataFromServer(userId, leadId) {
		// Page Size
		if (!viewModel.GoButton() && viewModel.Leads().length == 0) {
			return false;
		}
		else {
			viewModel.GoButton(false);
		}

		var pageSizeValue = $('#pagesize').val().toString().replace(/\s/g, '');
		var pagesize = parseInt(pageSizeValue, 10);
		if (!IsNumeric(pageSizeValue) || pagesize.toString() == 'NaN' || pagesize < 0 || pagesize > 100) {
			return false;
		}

		// Page Index
		var pageIndexValue = $('#pagecurrent').val().toString().replace(/\s/g, '');
		var pageindex = parseInt(pageIndexValue, 10);

		if (!IsNumeric(pageIndexValue) || pageindex.toString() == 'NaN' || pageindex < 0 || (pageindex > viewModel.MaxPageIndex() && FirstFilterGo == false)) {
			return false;
		}

		// Set pageindex = 1 if click go to filter
		// Filter options
		if (FirstFilterGo == true) {
			pageindex = 1;
		}
		var statusValue = $('#StatusSelectedValue').val();
		var leadSourceValue = $('#LeadSourceSelectedValue').val();
		var agentId = $('#UserSelectedValue').val();

		if (statusValue == undefined) { statusValue = ''; }
		if (leadSourceValue == undefined) { leadSourceValue = ''; }
		if (agentId == undefined) { agentId = ''; }

		// Range options
		var rangeDate = $('#RangeSelectedValue').val();
		var startDate = "";
		var endDate = "";
		if (rangeDate != undefined && rangeDate != null && rangeDate != '') {
			rangeArray = rangeDate.split('|');
			startDate = rangeArray[0];
			endDate = rangeArray[1];
		}

		// Priority option
		var priority = "";
		if (prioritizedView) {
			priority = prioritizedView;
		}

		// Assign
		var dataPost = {
			"pagesize": pagesize,
			"pagecurrent": pageindex,
			"sortby": viewModel.ColName(),
			"sortorder": viewModel.SortOrder(),
			"status": statusValue,
			"campain": leadSourceValue,
			"agent": agentId,
			"startdate": startDate,
			"enddate": endDate,
			"priority": priority,
			"userid": userId,
			"leadid": leadId
		};

		var urlPost = "/Lead/GetData";

		// Reset false for diferent behavior
		FirstFilterGo = false;
		closePopup();

		// Json Get function to retrive data from server
		openProcess();

		// Ajax request
		// Build a list params
		// Call a request
		// Handle reponse
		$.ajax({
			type: "POST",
			url: urlPost,
			data: dataPost,
			dataType: "json",
			success: function (data, textStatus, jqXHR) {
				if (data.Error == undefined || data.Error == null) {
					viewModel.CurrentPageIndex(data.TotalLead == 0 ? 0 : data.PageIndex);
					viewModel.MaxPageIndex(data.TotalPages);
					viewModel.PageSize(data.PageSize);
					viewModel.TotalLead(data.TotalLead);
					viewModel.Leads(data.LeadsourceList == null ? [] : data.LeadsourceList);

					// Refresh tooltip
					hascounts();
					nocounts();

					// Stop progress bar
					hideProcess();
					closePopup();
				}
				else {
					// Stop progress bar
					hideProcess();
					showPopupError();
				}
			},
			error: function (xhr, status, error) {
				// Stop progress bar
				hideProcess();
				showPopupError();
			}
		});

	}

	// End Ajax request

	// Call object refresh data
	this.RefreshDataByPageSize = function () {
		LoadDataFromServer(0, 0);
	};
	this.RefreshDataByPageIndex = function () {
		LoadDataFromServer(0, 0);
	};
};

var FirstFilterGo = false;

ko.applyBindings(viewModel, document.getElementById("main"));

/* onload document */
$(document).ready(function () {
	$('#pagesize').removeClass('text-active');
	$('#pagecurrent').removeClass('text-active');
	$('#pagesize').data('lastValue', $('#pagesize').val());
	$('#pagecurrent').data('lastValue', $('#pagecurrent').val());

	// Key down, handle only for IE
	$('#pagesize').live('keydown', function (e) {
		var keyCode = e.keyCode || e.which;
		if (is_ie && keyCode == 13) {
			var lastValue = $('#pagesize').data('lastValue');
			var currentvalue = $('#pagesize').val().toString().replace(/\s/g, '');

			//console.log('last: ' + lastValue + ', current: ' + currentvalue);

			if (currentvalue != lastValue && lastValue != undefined) {
				var pagesize = parseInt(currentvalue, 10);

				if (!IsNumeric(currentvalue) || pagesize.toString() == 'NaN' || pagesize < 1 || pagesize > 100) {
					//viewModel.PageSizeText("* Please enter a number between 1 - 100");
				}
				else {
					$('#pagesize').data('lastValue', currentvalue);
					$('#pagecurrent').val("1");

					e.preventDefault();
					viewModel.RefreshDataByPageSize();

					return false;
				}
			}
			else {
				$('#pagesize').data('lastValue', currentvalue);
			}
		}
	});
	$('#pagecurrent').live('keydown', function (e) {
		var keyCode = e.keyCode || e.which;

		if (is_ie && keyCode == 13) {
			var lastValue = $('#pagecurrent').data('lastValue');
			var currentvalue = $('#pagecurrent').val().toString().replace(/\s/g, '');
			var pageindex = parseInt(currentvalue, 10);
			//console.log('last: ' + lastValue + ', current: ' + currentvalue);

			if (currentvalue != lastValue && lastValue != undefined) {
				if (!IsNumeric(currentvalue) || currentvalue == "" || currentvalue.toString() == 'NaN' || !IsNumeric(currentvalue) || pageindex < 1 || pageindex > viewModel.MaxPageIndex()) {
					//$('#pagecurrent').data('lastValue', currentvalue);
				}
				else {
					$('#pagecurrent').data('lastValue', currentvalue);
					e.preventDefault();
					// call custom function here
					viewModel.RefreshDataByPageIndex();
				}
			}
			else {
				$('#pagecurrent').data('lastValue', currentvalue);
			}
		}
	});


	// Handle input tag blur
	$('#pagesize').change(function (e) {
		var lastValue = $('#pagesize').data('lastValue');
		var pagevalue = $('#pagesize').val().toString().replace(/\s/g, '');
		var pagesize = parseInt(pagevalue, 10);

		if (lastValue != pagevalue) {
			if (!IsNumeric(pagevalue) || pagesize.toString() == 'NaN' || pagesize < 1 || pagesize > 100) {
				//viewModel.PageSizeText("* Please enter a number between 1 - 100");
			}
			else {
				$('#pagesize').data('lastValue', pagevalue);
				$('#pagecurrent').val("1");
				e.preventDefault();
				viewModel.RefreshDataByPageSize();
			}
		}
		else {
			$('#pagesize').data('lastValue', pagevalue);
		}
	});
	$('#pagecurrent').change(function (e) {
		var lastValue = $('#pagecurrent').data('lastValue');
		var pagevalue = $('#pagecurrent').val().toString().replace(/\s/g, '');
		var pageindex = parseInt(pagevalue, 10);

		if (lastValue != pagevalue) {
			if (!IsNumeric(pagevalue) || pagevalue == "") {
				//viewModel.PageCurrentText("* Please enter a number between 1 - " + viewModel.MaxPageIndex() + " ");
			}
			else if (pagevalue.toString() == 'NaN' || !IsNumeric(pagevalue) || pageindex < 1 || pageindex > viewModel.MaxPageIndex()) {
				//viewModel.PageCurrentText("* Please enter a number between 1 - " + viewModel.MaxPageIndex() + " ");
			}
			else {
				$('#pagecurrent').data('lastValue', pagevalue);
				e.preventDefault();
				viewModel.RefreshDataByPageIndex();
			}
		}
		else {
			$('#pagecurrent').data('lastValue', pagevalue);
		}
	});

	// Show/hide priority view messages
	var showPriorityMessage = $.cookie("showPriorityMessage");
	if (showPriorityMessage == "false") {
		$('#prioritybubble').hide();
	}
	else {
		$('#prioritybubble').show();
	}

	// mouse over/out
	$('.bubble').mouseover(function () {
		$('#prioritybubble').show();
	});
	$('.bubbleinfo').mouseover(function () {
		$('#prioritybubble').show();
	});
	$('.bubbleinfo').mouseout(function () {
		$('#prioritybubble').hide();
	});
});
function viewPriorityMessage(display) {
	$('#prioritybubble').hide();
	$.cookie("showPriorityMessage", "false", { path: '/', expires: 365 });
	return false;
}
